`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    19:32:48 07/05/2015 
// Design Name: 
// Module Name:    adc_drive 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module adc_drive(dclk,eoc,sdo,sclk,sdi,csb,convstb,vt_adc,avclk);
	input dclk;//adc_driver clock signal 5MHZ
	input sdo;//adc serial output
	input eoc;//adc end of conversion
	output sdi;//output to adc as command word
	output csb;//adc chip select,active low
	output convstb;//adc manual conversion,active low
	output sclk;//adc serial output clock 2.5MHZ
	output avclk;//adc parall output clock 61.73kHZ
	output [13:0] vt_adc;//output 14 bit data
	
	reg sdi=0;
	reg sclk=0;
	reg csb=1;
	reg convstb=1;
	reg avclk=1;
	reg [6:0] state=7'b0;//82 state 0~81
	reg [13:0] d;//s2p
	reg [13:0] dout;//dout
	reg [1:0] s=2'b0;//s=0,reset;s=1,cmr read;s=2,read data

	//state
	always @(negedge dclk) begin
		state<=(state==80)?0:state+1;
	end
	
	//convstb
	always @(negedge dclk) begin
		if(s==2) convstb<=(state==0)?0:1;
	end
	
	//csb
	always @(negedge dclk) begin
		csb<=(state>=46 && state<=78)?0:1; 
	end
	
	//sclk
	always @(negedge dclk) begin
		if(state>=47 && state<=78)
			sclk<=~sclk; 
	end
	
	//s
	always @(negedge dclk) begin
		if(s<2) 
			if(state==80) s<=s+1;
	end
	
	//sdi
	always @(negedge dclk) begin
		case(state)
			47:sdi<=1;
			49:sdi<=1;
			51:sdi<=s==0?1:0;
			53:sdi<=s==0?0:1;
			55,57,59,61,63,65,67,69,71,73,75:
				if(s==0) sdi<=1;
			77:
				if(s==0) sdi<=0;
		endcase
	end		

	//d serial to parrell
	always @(negedge dclk) begin
		if(s==2)
			case(state)
				47,49,51,53,55,57,59,
				61,63,65,67,69,71,73: d<={d[12:0],sdo};
			endcase
	end

	//dout
	always @(negedge dclk) begin
		if(state==75) dout<=d;
	end

  //aclk
  always @(negedge dclk) begin
    if(s==2)
      if(state==77 || state==80)
        avclk=~avclk; 
  end
endmodule
